package com.wy.controller;

import com.wy.common.R;
import com.wy.entity.Category;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.mutable.Mutable;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.UUID;

/**
 * 公共控制类,文件上传
 */
@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${RuiJi.path}")
    private String basePath;
    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R<String> update(MultipartFile file) {
        // 这里的file是一个临时的文件,存放在c盘目录下,需要将其存放到别的目录,否则此次执行结束文件丢失
        log.info(file.toString());
        // 1.获取文件的类型
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        // 2.避免文件重复,利用UUID重新生成文件名
        String fileName = UUID.randomUUID().toString() + suffix;
        // 3.获取指定目录
        File dir = new File(basePath);
        if (!dir.exists()) {
            //目录不存在,创建目录
            dir.mkdirs();
        }
        try {
            //将文件上传到指定目录
            file.transferTo(new File(basePath + fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(fileName);
    }

    /**
     * 文件下载
     * @param name
     * @param response
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        try {
            //输入流,读取文件内容
            FileInputStream fileInputStream = new FileInputStream(new File(basePath + name));
            //输出流,将文件回流浏览器,在页面展示图片
            ServletOutputStream outputStream = response.getOutputStream();

            response.setContentType("image/jpeg");
            //io流缓存区
            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }
            //关闭资源
            outputStream.close();
            fileInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
